package com.party.admin.web.controller.mall;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.party.admin.web.dto.AjaxResult;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.mall.MallBrand;
import com.party.core.model.mall.MallCategory;
import com.party.core.model.mall.MallSpec;
import com.party.core.service.mall.IMallBrandService;
import com.party.core.service.mall.IMallCategoryService;
import com.party.core.service.mall.IMallSpecService;
import com.party.core.service.mall.biz.GoodsCategoryBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * 商城类型控制器
 * Created by wei.li
 *
 * @date 2017/8/18 0018
 * @time 17:08
 */

@Controller
@RequestMapping(value = "mall/category")
public class MallCategoryController {
    @Autowired
    private GoodsCategoryBizService goodsCategoryBizService;
    @Autowired
    private IMallCategoryService mallCategoryService;
    @Autowired
    private IMallBrandService mallBrandService;
    @Autowired
    private IMallSpecService mallSpecService;


    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 选择商城分类列表
     *
     * @param mallCategory 分类查询信息
     * @param isMulti      是否多选
     * @param categoryIds  已选择分类IDS
     * @param page         分页参数
     * @return
     */
    @RequestMapping(value = "selectCategory")
    public ModelAndView selectCategory(MallCategory mallCategory, Integer isMulti, String categoryIds, Page page) {
        page.setLimit(3);
        ModelAndView modelAndView = new ModelAndView("mall/category/selectCategory");
        List<MallCategory> list = mallCategoryService.listPage(mallCategory, page);
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        modelAndView.addObject("categoryIds", categoryIds);
        modelAndView.addObject("isMulti", isMulti);

        Set<String> allCategoryIds = Sets.newHashSet();
        if (StringUtils.isNotEmpty(categoryIds)) {
            allCategoryIds.addAll(Arrays.asList(categoryIds.split(",")));
        }
        if (allCategoryIds.size() > 0) {
            List<MallCategory> mallCategories = mallCategoryService.batchList(allCategoryIds, new MallCategory(), null);
            mallCategories = LangUtils.transform(mallCategories, input -> {
                MallCategory category = new MallCategory();
                category.setId(input.getId());
                category.setName(input.getName());
                return category;
            });
            modelAndView.addObject("categoryJson", JSONObject.toJSONString(mallCategories));
        } else {
            modelAndView.addObject("categoryJson", JSONObject.toJSONString(new ArrayList<MallCategory>()));
        }
        return modelAndView;
    }

    /**
     * 商城分类列表
     *
     * @param mallCategory 类型
     * @param page         分页参数
     * @return 交互数据
     */
    @RequestMapping(value = "list")
    public ModelAndView listNew(MallCategory mallCategory, Page page) {
        page.setLimit(20);
        ModelAndView modelAndView = new ModelAndView("mall/category/categoryList");
        List<MallCategory> list = mallCategoryService.listPage(mallCategory, page);
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        return modelAndView;
    }


    /**selectCategory
     * 商城类型视图
     *
     * @param mallCategory 分类信息
     * @return 交互数据
     */
    @RequestMapping(value = "categoryForm")
    public ModelAndView categoryForm(MallCategory mallCategory, Integer type) {
        ModelAndView modelAndView = new ModelAndView("mall/category/addCategory");
        if (StringUtils.isNotEmpty(mallCategory.getId())) {
            mallCategory = mallCategoryService.get(mallCategory.getId());
            modelAndView.addObject("mallCategory", mallCategory);
        }
        List<MallCategory> list = mallCategoryService.selectCategory();
        modelAndView.addObject("type", type);
        modelAndView.addObject("list", list);
        modelAndView.addObject("parentId", mallCategory.getParentId());
        return modelAndView;
    }

    /**
     * 商城类型保存
     *
     * @param mallCategory 商城类型
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult save(MallCategory mallCategory) {
        try {
            if (Strings.isNullOrEmpty(mallCategory.getId())) {
                mallCategoryService.insert(mallCategory);
            } else {
                mallCategoryService.update(mallCategory);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存分类异常", e);
            return AjaxResult.error("保存分类异常");
        }
    }

    /**
     * 删除商城类型
     *
     * @param id 编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        try {
            MallCategory mallCategory = mallCategoryService.get(id);
            if (StringUtils.isEmpty(mallCategory.getParentId())) {
                //该分类下有子级分类，不能删除
                List<MallCategory> list = mallCategoryService.getByParentId(id);
                if (list.size() > 0) {
                    return AjaxResult.error("该分类下已有子类，不能删除");
                }
            }
            boolean deleteFlag = goodsCategoryBizService.checkDelete(id);
            if (!deleteFlag) {
                return AjaxResult.error("已分配不能删除");
            }
            mallCategoryService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("分类删除失败", e);
            return AjaxResult.error("分类删除失败");
        }
    }

    /**
     * 分类规格列表
     *
     * @param categoryId
     * @return
     */
    @RequestMapping("specList")
    public ModelAndView categorySpecList(String categoryId) {
        ModelAndView mv = new ModelAndView("mall/spec/categorySpecList");
        MallCategory mallCategory = mallCategoryService.get(categoryId);
        mv.addObject("mallCategory", mallCategory);

        List<MallSpec> specList = mallSpecService.findByCategoryId(categoryId);
        mv.addObject("list", specList);
        return mv;
    }

    /**
     * 分类品牌列表
     *
     * @param categoryId 分类id
     * @return
     */
    @RequestMapping(value = "brandList")
    public ModelAndView categoryBrandList(String categoryId) {
        ModelAndView mv = new ModelAndView("mall/brand/categoryBrandList");
        MallCategory mallCategory = mallCategoryService.get(categoryId);
        mv.addObject("mallCategory", mallCategory);

        List<MallBrand> brandList = mallBrandService.findByCategoryId(categoryId);
        mv.addObject("list", brandList);
        return mv;
    }

    /**
     * 验证分类唯一性
     *
     * @param name     分类名称
     * @param id       分类编号
     * @param parentId 一级分类编号
     * @return
     */
    @ResponseBody
    @RequestMapping("verifyName")
    public AjaxResult verifyName(String name, String id, String parentId) {
        if (StringUtils.isEmpty(name)) {
            return AjaxResult.error("分类名称不能为空");
        }
        List<MallCategory> mallCategories = mallCategoryService.findByName(name, parentId);
        if (mallCategories.size() > 0) {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error("分类名称已存在");
            }
            boolean flag = false;
            for (MallCategory db : mallCategories) {
                if (db.getId().equals(id)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error("分类名称已存在");
            }
        }
        return AjaxResult.success();
    }
}
